package com.amqr.movetest.activity;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amqr.movetest.R;
import com.amqr.movetest.bean.SimpleVpBean;

import java.util.ArrayList;
import java.util.List;

/**
 * User: LJM
 * Date&Time: 2017-05-17 & 20:37
 * Describe: Describe Text
 * 添加轮播点
 */
public class BannerTwoVpActivity extends AppCompatActivity {

    private ViewPager mVpSimple;
    private List<View> viewList;
    List<SimpleVpBean> simpleVpBeanList;

    private int currentItem;
    private int count;
    private boolean isAutoPlay;
    private Handler handler;
    private int delay = 3000;

    private Animator animatorToLarge;
    private Animator animatorToSmall;


    private SparseBooleanArray isLarge;
    private LinearLayout llDot;


    private int dotSize = 12;
    private int dotSpace = 12;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_banner_two_vp);
        mVpSimple = (ViewPager) findViewById(R.id.mVpSimple);
        llDot = (LinearLayout) findViewById(R.id.ll_dot);

        getDataSource();
        count = simpleVpBeanList.size();
        fillViewList();

        // 初始化Animator
        initAnimator();

        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(viewList);
        mVpSimple.setAdapter(myPagerAdapter);

        // 从第1张图片开始（位置刚好也是1，注意：0位置现在是最后一张图片）
        currentItem = 1;
        mVpSimple.setCurrentItem(1);

        mVpSimple.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 遍历一遍子View，设置相应的背景。
                for (int i = 0; i < llDot.getChildCount(); i++) {
                    if (i == position - 1) {// 被选中
                        llDot.getChildAt(i).setBackgroundResource(R.drawable.dot_selected);
                        if (!isLarge.get(i)) {
                            animatorToLarge.setTarget(llDot.getChildAt(i));
                            animatorToLarge.start();
                            isLarge.put(i, true);
                        }
                    } else {// 未被选中
                        llDot.getChildAt(i).setBackgroundResource(R.drawable.dot_unselected);
                        if (isLarge.get(i)) {
                            animatorToSmall.setTarget(llDot.getChildAt(i));
                            animatorToSmall.start();
                            isLarge.put(i, false);
                        }
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    // 闲置中
                    case ViewPager.SCROLL_STATE_IDLE:
                        if (mVpSimple.getCurrentItem() == 0) {
                            mVpSimple.setCurrentItem(count, false);
                        } else if (mVpSimple.getCurrentItem() == count + 1) {
                            mVpSimple.setCurrentItem(1, false);
                        }
                        currentItem = mVpSimple.getCurrentItem();
                        isAutoPlay = true;
                        break;
                    // 拖动中
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        isAutoPlay = false;
                        break;
                    // 设置中
                    case ViewPager.SCROLL_STATE_SETTLING:
                        isAutoPlay = true;
                        break;
                }

            }
        });

        // 设置指示器
        setIndicator();
        startPlay();
    }


    /**
     * 开始自动播放
     */
    private void startPlay() {
        // 如果少于2张就不用自动播放了
        if (count < 2) {
            isAutoPlay = false;
        } else {
            isAutoPlay = true;
            handler = new Handler();
            handler.postDelayed(task, delay);
        }
    }

    private Runnable task = new Runnable() {
        @Override
        public void run() {
            if (isAutoPlay) {
                // 位置循环
                currentItem = currentItem % (count + 1) + 1;
                // 正常每隔3秒播放一张图片
                mVpSimple.setCurrentItem(currentItem);
                handler.postDelayed(task, delay);
            } else {
                // 如果处于拖拽状态停止自动播放，会每隔5秒检查一次是否可以正常自动播放。
                handler.postDelayed(task, 5000);
            }
        }
    };


    private void initAnimator() {
        animatorToLarge = AnimatorInflater.loadAnimator(this, R.animator.scale_to_large);
        animatorToSmall = AnimatorInflater.loadAnimator(this, R.animator.scale_to_small);
    }


    /**
     * 设置指示器
     */
    private void setIndicator() {
        isLarge = new SparseBooleanArray();
        // 记得创建前先清空数据，否则会受遗留数据的影响。
        llDot.removeAllViews();
        for (int i = 0; i < count; i++) {
            View view = new View(this);
            view.setBackgroundResource(R.drawable.dot_unselected);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dotSize, dotSize);
            layoutParams.leftMargin = dotSpace / 2;
            layoutParams.rightMargin = dotSpace / 2;
            layoutParams.topMargin = dotSpace / 2;
            layoutParams.bottomMargin = dotSpace / 2;
            llDot.addView(view, layoutParams);
            isLarge.put(i, false);
        }
        llDot.getChildAt(0).setBackgroundResource(R.drawable.dot_selected);
        animatorToLarge.setTarget(llDot.getChildAt(0));
        animatorToLarge.start();
        isLarge.put(0, true);
    }

    // =============
    public class MyPagerAdapter extends PagerAdapter {
        private List<View> viewLists;
        public MyPagerAdapter() {
        }

        public MyPagerAdapter(List<View> viewLists) {
            super();
            this.viewLists = viewLists;
        }

        @Override
        public int getCount() {
            return viewLists.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(viewLists.get(position));
            return viewLists.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    private void fillViewList() {
        viewList = new ArrayList<View>();

        for (int i = 0;i<count+2;i++){

            View waitAddView = getLayoutInflater().inflate(R.layout.item_simple_vp_page,null,false);


            SimpleVpBean simpleVpBean = null;
            if (i == 0) {// 将最前面一页设置成本来最后的那页
                simpleVpBean = simpleVpBeanList.get(count-1);
            } else if (i == count + 1) {// 将最后面一页设置成本来最前的那页
                simpleVpBean = simpleVpBeanList.get(0);
            } else {
                simpleVpBean = simpleVpBeanList.get(i-1);
            }
            TextView mTvTop = (TextView) waitAddView.findViewById(R.id.mTvTop);
            TextView mTvBot = (TextView) waitAddView.findViewById(R.id.mTvBot);
            mTvTop.setText(simpleVpBean.top);
            mTvBot.setText(simpleVpBean.bot);

            Log.d("TTT","fillViewList  "+ i+"  simpleVpBean "+simpleVpBean.top);

            if(i%2==0){
                waitAddView.setBackgroundColor(ContextCompat.getColor(this,R.color.colorAccent));
            }else{
                waitAddView.setBackgroundColor(ContextCompat.getColor(this,R.color.colorPrimary));
            }
            viewList.add(waitAddView);
        }

    }

    private void getDataSource() {
        simpleVpBeanList = new ArrayList<>();
        SimpleVpBean simpleVpBean0 = new SimpleVpBean();
        simpleVpBean0.top ="page0";
        simpleVpBean0.bot ="孙悟空";

        SimpleVpBean simpleVpBean1 = new SimpleVpBean();
        simpleVpBean1.top ="page1";
        simpleVpBean1.bot ="路飞";

        SimpleVpBean simpleVpBean2 = new SimpleVpBean();
        simpleVpBean2.top ="page2";
        simpleVpBean2.bot ="马三立";

        simpleVpBeanList.add(simpleVpBean0);
        simpleVpBeanList.add(simpleVpBean1);
        simpleVpBeanList.add(simpleVpBean2);
    }
}
